/*
    BibleNotebook - A bible reader software
    Copyright (C) 2014  Williams Fernando Lopez

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
 */

/*
 * DictionariesPanel.java
 * Williams Lopez
 * Created on Nov 14, 2013, 10:50:57 AM
 */

package com.simplebible.ui.components;

import java.io.IOException;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.SwingUtilities;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import wl.util.TextResourcesUtil;
import wl.util.Utils;
import com.simplebible.dictionary.DictionaryHTMLRenderer;
import com.simplebible.objects.Preferences;

/**
 *
 * @author Williams Lopez
 */
public class DictionariesPanel extends javax.swing.JPanel {

    private static int PANTALLA_ROOT_MENU = 1;
    private static int PANTALLA_MENU = 2;
    private static int PANTALLA_MENU_KEY = 3;
    private static int PANTALLA_FIND_DEFINITION = 4;

    int pantallaActual = 1;
    String lastKey = null;
    String lastDefinition = null;
    String lastDictionary = null;

    boolean searchingWord = false;
    ImageIcon loadingGif;

    /** Creates new form DictionariesPanel */
    public DictionariesPanel() {
        initComponents();
        loadingGif = new ImageIcon(getClass().getResource("/simplebible/ui/img/loading16.gif"));
        try{
            TextResourcesUtil.registrarComponente(this);
        }catch(Exception e){
            Utils.printToLog("Error al registrar los componentes con TextResourcesUtil.registrarComponente", e, Preferences.LOG_LEVEL_ERROR);
        }

        this.jTextPane1.addHyperlinkListener(new HyperlinkListener() {

            public void hyperlinkUpdate(HyperlinkEvent e) {
                try {
                    if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                        String[] info = e.getDescription().split(":");
                        String cmd = info[0];
                        String dat = info[1];
                        if (cmd.equalsIgnoreCase("moretext")) {
                            String[] moreInfo = dat.split("&");
                            setWordDefinitions(moreInfo[1], moreInfo[0]);
                        } else if (cmd.equalsIgnoreCase("lesstext")) {
                            String[] moreInfo = dat.split("&");
                            setWordDefinitions(moreInfo[1]);
                        } else if (cmd.equalsIgnoreCase("similar")) {
                            String[] moreInfo = dat.split("&");
                            if (moreInfo.length < 2 || moreInfo[0].equals("null")) {
                                setWordDefinitions(moreInfo[1]);
                            } else {
                                setWordDefinitions(moreInfo[1], moreInfo[0]);
                            }
                        } else if (cmd.equalsIgnoreCase("dictionary")) {
                            String[] moreInfo = dat.split("&");
                            setDictionaryMenuBackground(moreInfo[0], moreInfo[1]);
                        } else if (cmd.equalsIgnoreCase("dictkey")) {
                            String[] moreInfo = dat.split("&");
                            setDictionaryMenuKeyBackground(moreInfo[0], moreInfo[1], Integer.parseInt(moreInfo[2]));
                        }
                    }
                } catch (Exception ex) {
                    MainPanel.showNotification("generic_error", ex);
                    Utils.printToLog("Error al realizar la accion de hyperlink:"+ex.getMessage(), ex, Preferences.LOG_LEVEL_ERROR);
                }
            }
        });
    }


    private void setPantallaActual(int i) throws Exception{

        if(i<1) i = 1;
        if(i>4) i = 4;

        switch(i){
            case 1: setDictionaryRootMenuBackground(); break;
            case 2:{
                if(lastDictionary!=null){
                    setDictionaryMenuBackground(lastDictionary,lastKey);
                }else{
                    setDictionaryRootMenuBackground();
                }
            } break;
            case 3:{
                if(lastDictionary!=null && lastKey!=null){
                    setDictionaryMenuKeyBackground(lastDictionary, lastKey,0);
                }else if(lastDictionary!=null){
                    setDictionaryMenuBackground(lastDictionary,lastKey);
                }else{
                    setDictionaryRootMenuBackground();
                }
                break;
            }
            case 4:{
                if(lastDefinition!=null){
                    findAndSetWordDefinition(lastDefinition, lastDictionary, true);
                }if(lastDictionary!=null && lastKey!=null){
                    setDictionaryMenuKeyBackground(lastDictionary, lastKey,0);
                }else if(lastDictionary!=null){
                    setDictionaryMenuBackground(lastDictionary,lastKey);
                }else{
                    setDictionaryRootMenuBackground();
                }
            }
        }
    }



    public void setWordDefinitions(String word){
        setWordDefinitionBackground(word, null,true);
    }


    public void setWordDefinitions(String word,String dictionaryExpanded){
        setWordDefinitionBackground(word, dictionaryExpanded,true);
    }


    public void setDictionaryRootMenu() throws IOException{
        pantallaActual = PANTALLA_ROOT_MENU;
        this.jTextPane1.setText(DictionaryHTMLRenderer.getDictionaryRootMenu());
    }

    private void setDictionaryMenuKey(String dictid,String key,int page) throws IOException{
        lastDictionary = dictid;
        lastKey = key;
        pantallaActual = PANTALLA_MENU_KEY;
        this.jTextPane1.setText(DictionaryHTMLRenderer.getDictionaryMenuForKey(dictid, key, page));
    }

    private void setDictionaryMenu(String dictid,String key) throws IOException {
        lastDictionary = dictid;
        pantallaActual = PANTALLA_MENU;
        this.jTextPane1.setText(DictionaryHTMLRenderer.getDictionaryMenu(dictid,key));

    }

    private void findAndSetWordDefinition(String word,String dictionaryExpanded,boolean setWordInLabel) throws Exception{

        lastDefinition = word;
        pantallaActual = PANTALLA_FIND_DEFINITION;

        word = word.trim();
        
        if(word.equals("")){
            setDictionaryRootMenu();
            return;
        }


        if(setWordInLabel){
            jTextField1.setText(word);
        }



        String html = DictionaryHTMLRenderer.getDictionaryFountWords(word, dictionaryExpanded, setWordInLabel);


        final int scrollPos = this.jScrollPane1.getVerticalScrollBar().getValue();

        this.jTextPane1.setText(html);

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                int newScrollPos = scrollPos;
                int maxScrollPos = jScrollPane1.getVerticalScrollBar().getMaximum();
                if(scrollPos < 0){
                    newScrollPos = 0;
                }
                if(scrollPos>maxScrollPos){
                    newScrollPos = maxScrollPos;
                }
                jScrollPane1.getVerticalScrollBar().setValue(newScrollPos);
            }
        });
    }

    private void setDictionaryMenuKeyBackground(String dictid,String key, int page) throws IOException{
        final String id = dictid;
        final String fkey = key;
        final int fpage = page;
        Thread t = new Thread(){
            @Override
            public void run() {
                if (searchingWord) {
                    return;
                }
                Icon icono = jLabel1.getIcon();
                jLabel1.setIcon(loadingGif);
                searchingWord = true;
                try {
                    setDictionaryMenuKey(id,fkey,fpage);
                } catch (Exception e) {
                    MainPanel.showNotification("generic_error", e);
                    Utils.printToLog("Error al buscar la definicion", e, Preferences.LOG_LEVEL_ERROR);
                }
                searchingWord = false;
                jLabel1.setIcon(icono);
            }

        };
        t.start();
    }

    private void setDictionaryMenuBackground(String dictid,String key) {

        final String id = dictid;
        final String fkey = key;
        Thread t = new Thread(){
            @Override
            public void run() {
                if (searchingWord) {
                    return;
                }
                Icon icono = jLabel1.getIcon();
                jLabel1.setIcon(loadingGif);
                searchingWord = true;
                try {
                    setDictionaryMenu(id,fkey);
                } catch (Exception e) {
                    MainPanel.showNotification("generic_error", e);
                    Utils.printToLog("Error al buscar la definicion", e, Preferences.LOG_LEVEL_ERROR);
                }
                searchingWord = false;
                jLabel1.setIcon(icono);
            }

        };
        t.start();
    }

    public void setDictionaryRootMenuBackground(){
        Thread t = new Thread(){
            @Override
            public void run() {
                if (searchingWord) {
                    return;
                }
                Icon icono = jLabel1.getIcon();
                jLabel1.setIcon(loadingGif);
                searchingWord = true;
                try {
                    setDictionaryRootMenu();
                } catch (Exception e) {
                    MainPanel.showNotification("generic_error", e);
                    Utils.printToLog("Error al buscar la definicion", e, Preferences.LOG_LEVEL_ERROR);
                }
                searchingWord = false;
                jLabel1.setIcon(icono);
            }

        };
        t.start();
    }

    private void setWordDefinitionBackground(String word, String dictionaryExpanded,boolean setWordInLabel){

        final String fword = word;
        final String fdict = dictionaryExpanded;
        final boolean fsetword = setWordInLabel;

        Thread t = new Thread(){
            @Override
            public void run() {
                if (searchingWord) {
                    return;
                }
                Icon icono = jLabel1.getIcon();
                jLabel1.setIcon(loadingGif);
                searchingWord = true;
                try {
                    findAndSetWordDefinition(fword,fdict,fsetword);
                } catch (Exception e) {
                    MainPanel.showNotification("generic_error", e);
                    Utils.printToLog("Error al buscar la definicion", e, Preferences.LOG_LEVEL_ERROR);
                }
                searchingWord = false;
                jLabel1.setIcon(icono);
            }

        };
        t.start();
    }


  

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTextField1 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextPane1 = new javax.swing.JTextPane();
        buttonLabel1 = new wl.ui.ButtonLabel();

        setBackground(new java.awt.Color(255, 255, 255));

        jTextField1.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        jTextField1.setForeground(new java.awt.Color(153, 153, 153));
        jTextField1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204)));
        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextField1KeyReleased(evt);
            }
        });

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/simplebible/ui/img/filter16.png"))); // NOI18N

        jScrollPane1.setBorder(null);

        jTextPane1.setContentType("text/html");
        jTextPane1.setEditable(false);
        jScrollPane1.setViewportView(jTextPane1);

        buttonLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/simplebible/ui/img/arrow_turn_left.png"))); // NOI18N
        buttonLabel1.setText(".");
        buttonLabel1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonLabel1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 88, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE)
                        .addComponent(buttonLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1)
                        .addGap(11, 11, 11)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 179, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyReleased
        String word = jTextField1.getText();
        setWordDefinitionBackground(word, null, false);
    }//GEN-LAST:event_jTextField1KeyReleased

    private void buttonLabel1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonLabel1ActionPerformed
        try {
            setPantallaActual(pantallaActual-1);
        } catch (Exception e) {
            Utils.printToLog("Error al subir de pantalla", e, Preferences.LOG_LEVEL_ERROR);
        }

    }//GEN-LAST:event_buttonLabel1ActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private wl.ui.ButtonLabel buttonLabel1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextPane jTextPane1;
    // End of variables declaration//GEN-END:variables

}
